/*
 * SPDX-FileCopyrightText: 2020 Vlad Zahorodnii <vladzzag@gmail.com>
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
 */

import QtQuick 2.5
import QtQuick.Dialogs 1.2
import QtQuick.Layouts 1.0
import QtQuick.Controls 1.0 as QtControls
import QtQuick.Controls 2.3 as QtControls2
import QtPositioning 5.9

import org.kde.kcm 1.1 as KCM
import org.kde.kirigami 2.5 as Kirigami

import com.github.zzag.private.wallpaper 1.2

ColumnLayout {
    id: root

    property int cfg_FillMode
    property int cfg_UpdateInterval
    property string cfg_WallpaperId

    property alias cfg_AutoDetectLocation: autoDetectLocationCheckBox.checked
    property alias cfg_Latitude: latitudeSpinBox.value
    property alias cfg_Longitude: longitudeSpinBox.value

    function saveConfig() {
        // Uninstall all zombie wallpapers when the user clicks OK or Apply button.
        installer.uninstall(wallpapersModel.zombies());
    }

    Kirigami.FormLayout {
        twinFormLayouts: parentLayout

        QtControls2.ComboBox {
            id: positioningComboBox
            Kirigami.FormData.label: i18nd("plasma_wallpaper_com.github.zzag.wallpaper", "Fill Mode:")
            model: [
                {
                    "text": i18nd("plasma_wallpaper_com.github.zzag.wallpaper", "Scaled and Cropped"),
                    "value": Image.PreserveAspectCrop
                },
                {
                    "text": i18nd("plasma_wallpaper_com.github.zzag.wallpaper", "Scaled"),
                    "value": Image.Stretch
                },
                {
                    "text": i18nd("plasma_wallpaper_com.github.zzag.wallpaper", "Scaled, Keep Proportions"),
                    "value": Image.PreserveAspectFit
                },
                {
                    "text": i18nd("plasma_wallpaper_com.github.zzag.wallpaper", "Centered"),
                    "value": Image.Pad
                },
                {
                    "text": i18nd("plasma_wallpaper_com.github.zzag.wallpaper", "Tiled"),
                    "value": Image.Tile
                }
            ]

            textRole: "text"
            onActivated: cfg_FillMode = model[currentIndex]["value"]

            Component.onCompleted: {
                for (var i = 0; i < model.length; i++) {
                    if (model[i]["value"] == wallpaper.configuration.FillMode) {
                        positioningComboBox.currentIndex = i;
                        break;
                    }
                }
            }
        }

        QtControls2.CheckBox {
            id: autoDetectLocationCheckBox
            text: i18nd("plasma_wallpaper_com.github.zzag.wallpaper", "Automatically detect location")
        }

        QtControls.SpinBox {
            Kirigami.FormData.label: i18nd("plasma_wallpaper_com.github.zzag.wallpaper", "Latitude:")
            enabled: !autoDetectLocationCheckBox.checked
            visible: autoDetectLocationCheckBox.checked
            decimals: 2
            minimumValue: -90
            maximumValue: 90
            value: automaticLocationProvider.position.coordinate.latitude
        }

        QtControls.SpinBox {
            Kirigami.FormData.label: i18nd("plasma_wallpaper_com.github.zzag.wallpaper", "Longitude:")
            enabled: !autoDetectLocationCheckBox.checked
            visible: autoDetectLocationCheckBox.checked
            decimals: 2
            minimumValue: -180
            maximumValue: 180
            value: automaticLocationProvider.position.coordinate.longitude
        }

        QtControls.SpinBox {
            id: latitudeSpinBox
            Kirigami.FormData.label: i18nd("plasma_wallpaper_com.github.zzag.wallpaper", "Latitude:")
            decimals: 2
            minimumValue: -90
            maximumValue: 90
            visible: !autoDetectLocationCheckBox.checked
        }

        QtControls.SpinBox {
            id: longitudeSpinBox
            Kirigami.FormData.label: i18nd("plasma_wallpaper_com.github.zzag.wallpaper", "Longitude:")
            decimals: 2
            minimumValue: -180
            maximumValue: 180
            visible: !autoDetectLocationCheckBox.checked
        }

        QtControls.SpinBox {
            id: updateIntervalSpinBox
            Kirigami.FormData.label: i18nd("plasma_wallpaper_com.github.zzag.wallpaper", "Update Every:")
            maximumValue: 59
            minimumValue: 1
            suffix: i18ndp("plasma_wallpaper_com.github.zzag.wallpaper", " minute", " minutes", value)
            onValueChanged: cfg_UpdateInterval = value * 60000
            Component.onCompleted: value = wallpaper.configuration.UpdateInterval / 60000
        }
    }

    RowLayout {
        Kirigami.InlineMessage {
            id: installerErrorMessage
            Layout.fillWidth: true
            showCloseButton: true
            type: Kirigami.MessageType.Error
            text: installer.error
            visible: false
        }
    }

    KCM.GridView {
        id: wallpapersGrid

        Layout.fillWidth: true
        Layout.fillHeight: true

        function resetCurrentIndex() {
            view.currentIndex = wallpapersModel.indexOf(cfg_WallpaperId);
        }

        view.model: wallpapersModel
        view.delegate: KCM.GridDelegate {
            hoverEnabled: true
            text: model.name
            opacity: model.zombie ? 0.5 : 1
            toolTip: {
                if (model.author && model.license)
                    return i18ndc("plasma_wallpaper_com.github.zzag.wallpaper", "<image> by <author> (<license>)", "By %1 (%2)", model.author, model.license);
                if (model.license)
                    return i18ndc("plasma_wallpaper_com.github.zzag.wallpaper", "<image> (<license>)", "%1 (%2)", model.name, model.license);
                return model.name;
            }
            actions: [
                Kirigami.Action {
                    icon.name: "document-open-folder"
                    tooltip: i18nd("plasma_wallpaper_com.github.zzag.wallpaper", "Open Containing Folder")
                    onTriggered: Qt.openUrlExternally(model.folder)
                },
                Kirigami.Action {
                    icon.name: "edit-undo"
                    tooltip: i18nd("plasma_wallpaper_com.github.zzag.wallpaper", "Restore Wallpaper")
                    visible: model.zombie
                    onTriggered: model.zombie = false
                },
                Kirigami.Action {
                    icon.name: "edit-delete"
                    tooltip: i18nd("plasma_wallpaper_com.github.zzag.wallpaper", "Remove Wallpaper")
                    visible: !model.zombie && model.removable
                    onTriggered: model.zombie = true
                }
            ]
            thumbnail: Image {
                anchors.fill: parent
                fillMode: cfg_FillMode
                source: model.previewUrl
            }
            onClicked: {
                cfg_WallpaperId = model.id;
                wallpapersGrid.forceActiveFocus();
            }
        }

        Connections {
            target: wallpapersModel
            onRowsInserted: Qt.callLater(wallpapersGrid.resetCurrentIndex)
            onRowsRemoved: Qt.callLater(wallpapersGrid.resetCurrentIndex)
        }
        Connections {
            target: root
            onCfg_WallpaperIdChanged: Qt.callLater(wallpapersGrid.resetCurrentIndex)
        }

        Component.onCompleted: resetCurrentIndex()
    }

    FileDialog {
        id: wallpaperDialog
        title: i18nd("plasma_wallpaper_com.github.zzag.wallpaper", "Open Wallpaper")
        folder: shortcuts.home
        nameFilters: [i18nd("plasma_wallpaper_com.github.zzag.wallpaper", "Metadata file (metadata.json)")]
        selectExisting: true
        selectFolder: false
        selectMultiple: false
        onAccepted: installer.install(wallpaperDialog.fileUrl)
    }

    RowLayout {
        Layout.alignment: Qt.AlignRight

        QtControls2.Button {
            icon.name: "list-add"
            text: i18nd("plasma_wallpaper_com.github.zzag.wallpaper", "Add Wallpaper...")
            onClicked: wallpaperDialog.open()
        }
    }

    WallpapersModel {
        id: wallpapersModel
    }

    DynamicWallpaperInstaller {
        id: installer
        onInstalled: Qt.callLater(wallpapersModel.reload)
        onUninstalled: Qt.callLater(wallpapersModel.reload)
        onErrorChanged: installerErrorMessage.visible = true
    }

    PositionSource {
        id: automaticLocationProvider
        active: autoDetectLocationCheckBox.checked
    }

    Component.onCompleted: wallpapersModel.reload()
}
